package com.voxel.sense.infomsg.module.trace.map;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;

import com.amap.api.maps.AMap;
import com.amap.api.maps.CameraUpdateFactory;
import com.amap.api.maps.MapView;
import com.amap.api.maps.model.BitmapDescriptorFactory;
import com.amap.api.maps.model.LatLng;
import com.amap.api.maps.model.Marker;
import com.amap.api.maps.model.MarkerOptions;
import com.amap.api.maps.model.PolylineOptions;
import com.bigkoo.pickerview.builder.OptionsPickerBuilder;
import com.bigkoo.pickerview.listener.CustomListener;
import com.bigkoo.pickerview.listener.OnOptionsSelectListener;
import com.bigkoo.pickerview.view.OptionsPickerView;
import com.example.com.common.app.BViewActivity;
import com.example.com.common.utils.ListUtil;
import com.example.com.common.utils.NetworkUtils;
import com.example.com.common.utils.TimeUtils;
import com.example.com.common.utils.ToastUtil;
import com.voxel.sense.infomsg.R;
import com.voxel.sense.infomsg.data.bean.ClockInMarkerBean;
import com.voxel.sense.infomsg.module.trace.details.CheckinsDetailsActivity;
import com.voxel.sense.infomsg.view.titlebar.CommonTitleBar;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import cyy.example.com.facotry.Factory;
import cyy.example.com.facotry.constants.Constants;
import cyy.example.com.facotry.constants.IntentConstants;

/**
 * 查看打卡记录
 */
public class CheckinsRecordActivity extends BViewActivity<CheckinsRecordContract.Presenter>
        implements CheckinsRecordContract.View {
    @BindView(R.id.map)
    MapView mMapView;
    @BindView(R.id.titlebar)
    CommonTitleBar titlebar;
    @BindView(R.id.ib_details)
    ImageButton ib_details;
    AMap aMap;
    String mUserId;

    private OptionsPickerView mPvCustomOptions;//条件选择器
    private List<String> mDate;
    private String mUserName;
    private Marker mCurrenClickMarker;
    private List mYears;
    private List<List<String>> mMonths;
    private List<List<List<String>>> mDays;
    private boolean mIsNetLoad = true;

    public static void show(Context context, String userId, String userName) {
        if (context == null || userId == null)
            return;
        Intent intent = new Intent(context, CheckinsRecordActivity.class);
        intent.putExtra(IntentConstants.STRING_ID, userId);
        intent.putExtra(IntentConstants.STRING_NAME, userName);
        context.startActivity(intent);
    }


    /**
     * @param context
     * @param userId    用户id
     * @param userName  用户名
     * @param time      打卡时间
     * @param latitude  纬度
     * @param longitude 经度
     * @param flag      标记是否需要从网络加载数据
     */
    public static void show(Context context, String userId, String userName, String time, double latitude, double longitude, boolean flag) {
        if (context == null || userId == null)
            return;
        Intent intent = new Intent(context, CheckinsRecordActivity.class);
        intent.putExtra(IntentConstants.STRING_ID, userId);
        intent.putExtra(IntentConstants.STRING_NAME, userName);
        intent.putExtra(IntentConstants.STRING_TYPE, time);
        intent.putExtra(IntentConstants.LATITUDE, latitude);
        intent.putExtra(IntentConstants.LONGITUDE, longitude);
        intent.putExtra(IntentConstants.BOOLEAN_TYPE, flag);
        context.startActivity(intent);
    }

    public static void show(Context context, ArrayList<ClockInMarkerBean> datas, boolean flag) {
        if (context == null || ListUtil.isEmpty(datas))
            return;
        Intent intent = new Intent(context, CheckinsRecordActivity.class);
        intent.putExtra(IntentConstants.BOOLEAN_TYPE, flag);
        intent.putExtra(IntentConstants.OBJECT_TYPE, datas);
        context.startActivity(intent);
    }

    @Override
    protected int getContentLayoutId() {
        return R.layout.activity_checkins_record;
    }

    @Override
    protected CheckinsRecordContract.Presenter initPresenter() {
        return new CheckinsRecordPresenter(this);
    }

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mMapView.onCreate(savedInstanceState);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        //在activity执行onDestroy时执行mMapView.onDestroy()，销毁地图
        mMapView.onDestroy();
    }

    @Override
    protected void onResume() {
        super.onResume();
        //在activity执行onResume时执行mMapView.onResume ()，重新绘制加载地图
        mMapView.onResume();
    }

    @Override
    protected void onPause() {
        super.onPause();
        mMapView.onPause();
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        //在activity执行onSaveInstanceState时执行mMapView.onSaveInstanceState (outState)，保存地图当前的状态
        mMapView.onSaveInstanceState(outState);
    }

    @Override
    protected void initData() {
        super.initData();
        if (aMap == null) {
            aMap = mMapView.getMap();
        }

        mUserId = getIntent().getStringExtra(IntentConstants.STRING_ID);
        mUserName = getIntent().getStringExtra(IntentConstants.STRING_NAME);
        mIsNetLoad = getIntent().getBooleanExtra(IntentConstants.BOOLEAN_TYPE, true);

        ArrayList<ClockInMarkerBean> beans = (ArrayList<ClockInMarkerBean>) getIntent().getSerializableExtra(IntentConstants.OBJECT_TYPE);

        titlebar.setTitleText("打卡记录");

        aMap.moveCamera(CameraUpdateFactory.changeLatLng(new LatLng(22.7571200000, 113.8469900000)));

        if (mIsNetLoad) {
            //判断是否从网络加载数据，若是一传递了坐标信息，则不需要
            ib_details.setVisibility(View.VISIBLE);
            requestDateRecord();
            titlebar.setRightVisible(true);
            initCustomOptionPicker();
            titlebar.setRightImgAndLis(R.mipmap.icon_title_calendar, new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    //弹起日期列表，没有则请求
                    mPresenter.doLoadDateList(mUserId, mUserName, true);
                    if (mDate == null || mDate.size() < 1) {
                        requestDateRecord();
                        return;
                    }
                    mPvCustomOptions.show(titlebar.getIb_right());
                }
            });
        } else if (!ListUtil.isEmpty(beans)) {
            mPresenter.doHandlerClockBean(beans);
        } else {
            addMakerToMap();
        }

        //设置最小缩放的等级数值
        aMap.setMinZoomLevel(Constants.MAP_MIN_ZOOM_LEVEL);
        aMap.setMaxZoomLevel(Constants.MAP_MAX_ZOOM_LEVEL);
        aMap.moveCamera(CameraUpdateFactory.zoomTo(Constants.MAP_DEFAULT_ZOOM_LEVEL));
    }

    private void addMakerToMap() {
        double latitude = getIntent().getDoubleExtra(IntentConstants.LATITUDE, 0);
        double longitude = getIntent().getDoubleExtra(IntentConstants.LONGITUDE, 0);
        String time = getIntent().getStringExtra(IntentConstants.STRING_TYPE);
        if (latitude != 0 && longitude != 0 && !TextUtils.isEmpty(time)) {
            LatLng latLng = new LatLng(latitude, longitude);
            //TODO:
            String desc = String.format(Factory.app().getString(R.string.user_name_id), mUserName, mUserId);
            View view = View.inflate(this, R.layout.map_custom_marker, null);

            MarkerOptions draggable = new MarkerOptions()
                    .position(latLng)
                    .draggable(false)
                    .icon(BitmapDescriptorFactory.fromView(view))
                    .title(time)
                    .snippet(desc);

            aMap.addMarker(draggable);
            aMap.moveCamera(CameraUpdateFactory.changeLatLng(latLng));
        }
    }


    @OnClick(R.id.ib_details)
    public void onClickEvent(View v) {
        if (mDate != null && mDate.size() > 0) {
//            String firt = mDate.get(0);//首次打卡日期
//            String last = mDate.get(mDate.size()-1);//最后一次打卡日子
            Date latest = TimeUtils.string2Date(mDate.get(0), new SimpleDateFormat(Constants.TimeYMDFormat));
            Date first = TimeUtils.string2Date(mDate.get(mDate.size() - 1), new SimpleDateFormat(Constants.TimeYMDFormat));
            CheckinsDetailsActivity.show(this, mUserId, mUserName, first, latest);
        } else {
            ToastUtil.showToastLong(this,getString(R.string.no_clock_in_record));
        }
    }


    private void requestDateRecord() {
        if (NetworkUtils.isConnected()) {
            mPresenter.doLoadDateList(mUserId, mUserName, true);
        } else {
            ToastUtil.showToastLong(getApplicationContext(), getString(R.string.network_unavailable));
        }
    }

    @Override
    protected void initEven() {
        super.initEven();
        aMap.setOnMarkerClickListener(new AMap.OnMarkerClickListener() {
            @Override
            public boolean onMarkerClick(Marker marker) {
                mCurrenClickMarker = marker;
                marker.showInfoWindow();
                return true;
            }
        });
        aMap.setOnMapClickListener(new AMap.OnMapClickListener() {
            @Override
            public void onMapClick(LatLng latLng) {
                if (mCurrenClickMarker != null) {
                    mCurrenClickMarker.hideInfoWindow();
                }
            }
        });
    }

    @Override
    public void onAddMarker(List<MarkerOptions> data) {
        aMap.addMarkers((ArrayList<MarkerOptions>) data, true);
    }

    @Override
    public void onDrawLine(List<LatLng> datas) {
        PolylineOptions polygonOptions = new PolylineOptions();
        polygonOptions.addAll(datas);
        polygonOptions.color(R.color.blue_900);
        aMap.addPolyline(polygonOptions);
    }

    @Override
    public void onCleanMap() {
        aMap.clear();
    }

    @Override
    public void onUpDateList(List<String> list) {
        mPvCustomOptions.setPicker(list);
    }

    @Override
    public void onShowDateList() {
        mPvCustomOptions.show(titlebar.getIb_right());
    }

    @Override
    public void onUpDateList(List years, List months, List days, List<String> originalData) {
        mDate = originalData;
        mYears = years;
        mMonths = months;
        mDays = days;
        try {
            mPvCustomOptions.setPicker(years, months, days);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    //条件选择器初始化，自定义布局
    private void initCustomOptionPicker() {
        mPvCustomOptions = new OptionsPickerBuilder(this, new OnOptionsSelectListener() {
            @Override
            public void onOptionsSelect(int options1, int options2, int options3, View v) {
//                mPresenter.doLaodData(options1);
                mPresenter.doLaodData(mYears.get(options1) + mMonths.get(options1).get(options2) +
                        mDays.get(options1).get(options2).get(options3));
            }
        })
                .setLayoutRes(R.layout.pickerview_custom_options, new CustomListener() {//初始化布局
                    @Override
                    public void customLayout(View v) {
                        final TextView tvSubmit = v.findViewById(R.id.tv_finish);
                        ImageView ivCancel = v.findViewById(R.id.iv_cancel);
                        //点击完成
                        tvSubmit.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                mPvCustomOptions.returnData();
                                mPvCustomOptions.dismiss();
                            }
                        });
                        //点击取消
                        ivCancel.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                mPvCustomOptions.dismiss();
                            }
                        });
                    }
                })
                .build();
    }
}
